package com.middlegroup.pay.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeFastpayRefundQueryModel;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.middlegroup.common.enums.ChannelCode;
import com.middlegroup.common.enums.ConfigKeyEnums;
import com.middlegroup.common.exception.ErrorMsg;
import com.middlegroup.common.model.NotifyRequest;
import com.middlegroup.common.model.PayRequest;
import com.middlegroup.common.model.RefundRequestDto;
import com.middlegroup.common.model.TransResult;
import com.middlegroup.common.utils.DateUtils;
import com.middlegroup.pay.dto.AliReturnQueryOrderResponse;
import com.middlegroup.pay.entity.*;
import com.middlegroup.pay.mapper.RefundBillsMapper;
import com.middlegroup.pay.service.*;
import com.paypal.api.payments.Amount;
import com.paypal.api.payments.Refund;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author
 * @since 2019-08-07
 */
@Service
@Slf4j
public class AlipayServiceImpl implements AlipayService {

    @Resource
    private RestTemplate restTemplate;
    @Resource
    private ThirdBillsService thirdBillsService;
    @Resource
    private SystemCfgService systemCfgService;
    @Resource
    private InBillsService inBillsService;
    @Resource
    private RefundBillsService refundBillsService;
    @Resource
    private RefundBillsMapper refundBillsMapper;
    @Resource
    private InNotifyLogService inNotifyLogService;
    @Resource
    private OutNotifyLogService outNotifyLogService;
    @Resource
    private NotifyMerchantService notifyMerchantService;
    @Override
    public TransResult createAlipay(PayRequest request) {
        TransResult transResult = new TransResult();
        transResult.setBillNo(request.getBillNo());
        transResult.setMerchantBillNo(request.getMerchantBillNo());
        transResult.setAmount(request.getAmount());
        transResult.setTransStatus(0);
        transResult.setTransTime(System.currentTimeMillis());

        String category=request.getChannelCode().getCode();
        String appid = systemCfgService.getConfigString(category, ConfigKeyEnums.ALIAPPID.getName());
        String alirsa_private_key=systemCfgService.getConfigString(category,ConfigKeyEnums.ALIRSA_PRIVATE_KEY.getName());
        String alinotify_url=systemCfgService.getConfigString(category,ConfigKeyEnums.ALINOTIFY_URL.getName());
//        String alireturn_url=systemCfgService.getConfigString(category,ConfigKeyEnums.ALIRETURN_URL.getName());
        //取用户传过来的returnurl 可能为空
        String alireturn_url=request.getReturnUrl();
        String alicharset=systemCfgService.getConfigString(category,ConfigKeyEnums.ALICHARSET.getName());
        String aliformat=systemCfgService.getConfigString(category,ConfigKeyEnums.ALIFORMAT.getName());
        String alipay_public_key=systemCfgService.getConfigString(category,ConfigKeyEnums.ALIPAY_PUBLIC_KEY.getName());
        String signtype=systemCfgService.getConfigString(category,ConfigKeyEnums.SIGNTYPE.getName());
        String aliurl = systemCfgService.getConfigString(category,ConfigKeyEnums.ALIURL.getName());
        String timeout_express = systemCfgService.getConfigString(category,ConfigKeyEnums.TIMEOUT_EXPRESS.getName());

        if(StringUtils.isBlank(appid) || StringUtils.isBlank(alirsa_private_key) || StringUtils.isBlank(alinotify_url)
                || StringUtils.isBlank(alicharset) || StringUtils.isBlank(aliformat)
                || StringUtils.isBlank(alipay_public_key) || StringUtils.isBlank(signtype)|| StringUtils.isBlank(aliurl)|| StringUtils.isBlank(timeout_express)){
            transResult.setTransStatus(2);
            transResult.setMsg(ErrorMsg.INCOMPLETE_CONFIG_INFO);
            return transResult;
        }

//        // 销售产品码 必填
        String product_code="QUICK_WAP_WAY";
        /**********************/
        // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
        //调用RSA签名方式
        AlipayClient client = new DefaultAlipayClient(aliurl, appid, alirsa_private_key, aliformat, alicharset, alipay_public_key,signtype);
        AlipayTradeWapPayRequest alipay_request=new AlipayTradeWapPayRequest();

        // 封装请求支付信息
        AlipayTradeWapPayModel model=new AlipayTradeWapPayModel();
        model.setOutTradeNo(request.getBillNo());
        model.setSubject(request.getSubject());//标题
        model.setTotalAmount(request.getAmount().toString());
        model.setBody(request.getState());//描述 非必填
        model.setTimeoutExpress(timeout_express);
        model.setProductCode(product_code);

        alipay_request.setBizModel(model);
        // 设置异步通知地址
        alipay_request.setNotifyUrl(alinotify_url);
        // 设置同步地址
        if(StringUtils.isNotEmpty(alireturn_url)){
            alipay_request.setReturnUrl(alireturn_url);
        }
        // form表单生产
        String form = "";
        try {
            // 调用SDK生成表单
            form = aliurl + "?"+ client.sdkExecute(alipay_request).getBody();
        } catch (AlipayApiException e) {
            log.error("支付宝h5支付请求数据加密失败,billNo:{},error:{}",request.getBillNo(),e);
            transResult.setTransStatus(2);
            transResult.setMsg(ErrorMsg.DATA_ENCRYPTION_FAIL);
            return transResult;
        }
        ThirdBills thirdBills=new ThirdBills();
        thirdBills.setSubjectCode(request.getSubjectCode());
        thirdBills.setMerchantBillNo(request.getMerchantBillNo());
        thirdBills.setBillNo(request.getBillNo());
        thirdBills.setStatus(0);
        thirdBills.setMethod("createAlipay");
        thirdBills.setAmount(request.getAmount());
        thirdBills.setRequestUrl(aliurl);
        thirdBills.setRequestText(JSON.toJSONString(model));
        thirdBills.setBeginTime(System.currentTimeMillis());
        thirdBills.setResponseText((StringUtils.isNotBlank(form) && form.length()>4000)?form.substring(0,4000):form);
        thirdBills.setEndTime(System.currentTimeMillis());
        thirdBills.setCurrency(request.getTransCurrency());
        try {
            thirdBillsService.insert(thirdBills);
        } catch (Exception e) {
            log.error("支付宝h5支付插入第三方订单表异常,billNo:{},error:{}",request.getBillNo(),e);
        }
        transResult.setNextStepData(form);
        return transResult;
    }

    @Override
    public AliReturnQueryOrderResponse AlipayQuery(String merchantBillNo, String billNo) {

        /**********************/
        // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
        String category="alipay_h5";
        String appid = systemCfgService.getConfigString(category, ConfigKeyEnums.ALIAPPID.getName());
        String alirsa_private_key=systemCfgService.getConfigString(category,ConfigKeyEnums.ALIRSA_PRIVATE_KEY.getName());
        String alinotify_url=systemCfgService.getConfigString(category,ConfigKeyEnums.ALINOTIFY_URL.getName());
//        String alireturn_url=systemCfgService.getConfigString(category,ConfigKeyEnums.ALIRETURN_URL.getName());
        String alicharset=systemCfgService.getConfigString(category,ConfigKeyEnums.ALICHARSET.getName());
        String aliformat=systemCfgService.getConfigString(category,ConfigKeyEnums.ALIFORMAT.getName());
        String alipay_public_key=systemCfgService.getConfigString(category,ConfigKeyEnums.ALIPAY_PUBLIC_KEY.getName());
        String signtype=systemCfgService.getConfigString(category,ConfigKeyEnums.SIGNTYPE.getName());
        String aliurl = systemCfgService.getConfigString(category,ConfigKeyEnums.ALIURL.getName());
        String timeout_express = systemCfgService.getConfigString(category,ConfigKeyEnums.TIMEOUT_EXPRESS.getName());
        String alipay_public_key_ali = systemCfgService.getConfigString(category,ConfigKeyEnums.ALIPAY_PUBLIC_KEY_ALI.getName());
        AlipayClient client = new DefaultAlipayClient(aliurl, appid, alirsa_private_key, aliformat, alicharset, alipay_public_key_ali,signtype);
        AlipayTradeQueryRequest alipay_request = new AlipayTradeQueryRequest();

        AlipayTradeQueryModel model=new AlipayTradeQueryModel();
        model.setOutTradeNo(billNo);
//        model.setTradeNo(billNo);
        alipay_request.setBizModel(model);

        AlipayTradeQueryResponse alipay_response = null;
        AliReturnQueryOrderResponse jsonObject = null;
        try {
            alipay_response = client.execute(alipay_request);
            if(null != alipay_response && !"".equals(alipay_response)){
                jsonObject = JSONObject.parseObject(alipay_response.getBody(),AliReturnQueryOrderResponse.class);
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return jsonObject;
    }

    @Override
    public TransResult refundAlipay(RefundRequestDto refundRequest, TransResult transResult){
//        String merchantBillNo, String billNo, BigDecimal refundAmount, String remark, String notifyUrl, String refundCurrency, String outRequestNo

        InBills inBills = inBillsService.getByMerchantBillNo(refundRequest.getMerchantBillNo());
        Refund refund = new Refund();
        Amount amount = new Amount();
        amount.setCurrency(inBills.getCurrency());//币种
        amount.setTotal(refundRequest.getRefundAmount().toString());//金额
        refund.setAmount(amount);
        refund.setReason(refundRequest.getRemark());//退款原因
        ThirdBills thirdBills = new ThirdBills();
        thirdBills.setStatus(0);
        thirdBills.setRequestText(refund.toJSON());//请求体
        thirdBills.setBeginTime(System.currentTimeMillis());
        thirdBills.setMethod("refundAlipay");
        thirdBills.setSubjectCode(inBills.getSubjectCode());
        thirdBills.setMerchantBillNo(inBills.getMerchantBillNo());
        thirdBills.setBillNo(inBills.getBillNo());
        thirdBills.setCurrency(inBills.getCurrency());//币种
        thirdBills.setAmount(inBills.getAmount());
        thirdBillsService.insert(thirdBills);

        /**********************/
        // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
        String category= ChannelCode.alipay_h5.getCode();
        String appid = systemCfgService.getConfigString(category, ConfigKeyEnums.ALIAPPID.getName());
        String alirsa_private_key=systemCfgService.getConfigString(category,ConfigKeyEnums.ALIRSA_PRIVATE_KEY.getName());
        String alinotify_url=systemCfgService.getConfigString(category,ConfigKeyEnums.ALINOTIFY_URL.getName());
//        String alireturn_url=systemCfgService.getConfigString(category,ConfigKeyEnums.ALIRETURN_URL.getName());
        String alicharset=systemCfgService.getConfigString(category,ConfigKeyEnums.ALICHARSET.getName());
        String aliformat=systemCfgService.getConfigString(category,ConfigKeyEnums.ALIFORMAT.getName());
        String alipay_public_key=systemCfgService.getConfigString(category,ConfigKeyEnums.ALIPAY_PUBLIC_KEY.getName());
        String signtype=systemCfgService.getConfigString(category,ConfigKeyEnums.SIGNTYPE.getName());
        String aliurl = systemCfgService.getConfigString(category,ConfigKeyEnums.ALIURL.getName());
        String timeout_express = systemCfgService.getConfigString(category,ConfigKeyEnums.TIMEOUT_EXPRESS.getName());
        String alipay_public_key_ali = systemCfgService.getConfigString(category,ConfigKeyEnums.ALIPAY_PUBLIC_KEY_ALI.getName());

        if(StringUtils.isBlank(appid) || StringUtils.isBlank(alirsa_private_key) || StringUtils.isBlank(alinotify_url)
                || StringUtils.isBlank(alicharset) || StringUtils.isBlank(aliformat)
                || StringUtils.isBlank(alipay_public_key) || StringUtils.isBlank(signtype)|| StringUtils.isBlank(aliurl)|| StringUtils.isBlank(timeout_express)){
            transResult.setTransStatus(2);
            transResult.setMsg(ErrorMsg.INCOMPLETE_CONFIG_INFO);
            return transResult;
        }

        /**********************/
        // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
        //调用RSA签名方式
        AlipayClient client = new DefaultAlipayClient(aliurl, appid, alirsa_private_key, aliformat, alicharset, alipay_public_key_ali,signtype);
        AlipayTradeRefundRequest alipay_request = new AlipayTradeRefundRequest();
        AlipayTradeRefundModel model=new AlipayTradeRefundModel();
        model.setOutTradeNo(inBills.getBillNo());
//        model.setTradeNo(inBills.getOrderId());
        model.setRefundAmount(refundRequest.getRefundAmount().toString());
        model.setRefundReason(refundRequest.getRemark());
        model.setOutRequestNo(refundRequest.getMerchantRefundNo());
        alipay_request.setBizModel(model);

        AlipayTradeRefundResponse alipay_response = null;
        try {
            alipay_response = client.execute(alipay_request);
        } catch (AlipayApiException e) {
            log.error("阿里h5支付请求异常,billNo:{},error:{}", thirdBills.getBillNo(), e);
        }

        try {
            thirdBillsService.updateById(thirdBills);
        } catch (Exception e) {
            log.error("阿里h5支付确认插入第三方订单表t_third_bills状态异常,billNo:{},error:{}", thirdBills.getBillNo(), e);
        }
        transResult.setNextStepData(alipay_response.getBody());
        return transResult;
    }

    @Override
    public AliReturnQueryOrderResponse refundQueryAlipay(String outRequestNo) {
// SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
        String category="alipay_h5";
        String appid = systemCfgService.getConfigString(category, ConfigKeyEnums.ALIAPPID.getName());
        String alirsa_private_key=systemCfgService.getConfigString(category,ConfigKeyEnums.ALIRSA_PRIVATE_KEY.getName());
        String alinotify_url=systemCfgService.getConfigString(category,ConfigKeyEnums.ALINOTIFY_URL.getName());
//        String alireturn_url=systemCfgService.getConfigString(category,ConfigKeyEnums.ALIRETURN_URL.getName());
        String alicharset=systemCfgService.getConfigString(category,ConfigKeyEnums.ALICHARSET.getName());
        String aliformat=systemCfgService.getConfigString(category,ConfigKeyEnums.ALIFORMAT.getName());
        String alipay_public_key=systemCfgService.getConfigString(category,ConfigKeyEnums.ALIPAY_PUBLIC_KEY.getName());
        String signtype=systemCfgService.getConfigString(category,ConfigKeyEnums.SIGNTYPE.getName());
        String aliurl = systemCfgService.getConfigString(category,ConfigKeyEnums.ALIURL.getName());
        String timeout_express = systemCfgService.getConfigString(category,ConfigKeyEnums.TIMEOUT_EXPRESS.getName());
        String alipay_public_key_ali = systemCfgService.getConfigString(category,ConfigKeyEnums.ALIPAY_PUBLIC_KEY_ALI.getName());
        AlipayClient client = new DefaultAlipayClient(aliurl, appid, alirsa_private_key, aliformat, alicharset, alipay_public_key_ali,signtype);
        AlipayTradeQueryRequest alipay_request = new AlipayTradeQueryRequest();

        AlipayTradeFastpayRefundQueryModel model=new AlipayTradeFastpayRefundQueryModel();
//        model.setOutTradeNo(merchantBillNo);
        model.setTradeNo(outRequestNo);
//        model.setOutRequestNo(outRequestNo);
        alipay_request.setBizModel(model);

        AlipayTradeQueryResponse alipay_response = null;
        AliReturnQueryOrderResponse jsonObject = null;
        try {
            alipay_response = client.execute(alipay_request);
            if(null != alipay_response && !"".equals(alipay_response)){
                jsonObject = JSONObject.parseObject(alipay_response.getBody(),AliReturnQueryOrderResponse.class);
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    @Override
    public void aliPayH5Notify(HttpServletRequest request) throws Exception {
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//			valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        log.debug("支付宝回调-----" + params + ":" + JSON.toJSONString(params));
        String category = "alipay_h5";
        String appid = systemCfgService.getConfigString(category, ConfigKeyEnums.ALIAPPID.getName());
        String alirsa_private_key=systemCfgService.getConfigString(category,ConfigKeyEnums.ALIRSA_PRIVATE_KEY.getName());
        String alinotify_url=systemCfgService.getConfigString(category,ConfigKeyEnums.ALINOTIFY_URL.getName());
//        String alireturn_url=systemCfgService.getConfigString(category,ConfigKeyEnums.ALIRETURN_URL.getName());
        String alicharset=systemCfgService.getConfigString(category,ConfigKeyEnums.ALICHARSET.getName());
        String aliformat=systemCfgService.getConfigString(category,ConfigKeyEnums.ALIFORMAT.getName());
        String alipay_public_key=systemCfgService.getConfigString(category,ConfigKeyEnums.ALIPAY_PUBLIC_KEY.getName());
        String signtype=systemCfgService.getConfigString(category,ConfigKeyEnums.SIGNTYPE.getName());
        String aliurl = systemCfgService.getConfigString(category,ConfigKeyEnums.ALIURL.getName());
        String timeout_express = systemCfgService.getConfigString(category,ConfigKeyEnums.TIMEOUT_EXPRESS.getName());
        String alipay_public_key_ali = systemCfgService.getConfigString(category,ConfigKeyEnums.ALIPAY_PUBLIC_KEY_ALI.getName());

        if(StringUtils.isBlank(appid) || StringUtils.isBlank(alirsa_private_key) || StringUtils.isBlank(alinotify_url)
                || StringUtils.isBlank(alicharset) || StringUtils.isBlank(aliformat)|| StringUtils.isBlank(alipay_public_key_ali)
                || StringUtils.isBlank(alipay_public_key) || StringUtils.isBlank(signtype)|| StringUtils.isBlank(aliurl)|| StringUtils.isBlank(timeout_express)){

            log.debug("支付宝配置参数错误" + requestParams + ":" + requestParams);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipay_public_key_ali, alicharset, signtype); //调用SDK验证签名

        if(signVerified) {//验证成功
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
            //通知类型
            String notify_type = new String(request.getParameter("notify_type").getBytes("ISO-8859-1"),"UTF-8");
            log.debug("通知类型&&&&&&&&&&&" + notify_type+" 交易状态+#############" +  trade_status);
            InBills inBills = inBillsService.getByBillNo(out_trade_no);
            if(null == inBills || "".equals(inBills)){
                return;
            }
            RefundBills model = new RefundBills();
            model.setMerchantBillNo(inBills.getMerchantBillNo());
            model.setStatus(0);
            model.setAmount(new BigDecimal(total_amount));
            RefundBills refundBills = refundBillsMapper.selectOne(model);
            //状态为close 肯定是退款的 不为close判断金额 相等为支付 不相等为退款
            if( "TRADE_FINISHED".equals(trade_status)){

                //注意： 尚自习的订单没有退款功能, 这个条件判断是进不来的, 所以此处不必写代码
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            }else if ("TRADE_SUCCESS".equals(trade_status) ){
                if(total_amount.equals(inBills.getAmount().toString())){//支付
                    //TODO 记录主体回调数据
                    InNotifyLog inNotifyLog = new InNotifyLog();
                    inNotifyLog.setCallbackText(JSON.toJSONString(requestParams));
                    inNotifyLog.setMerchantBillNo(out_trade_no);
                    inNotifyLog.setStatus(0);
                    inNotifyLog.setTransNo(trade_no);
                    //TODO 接收回调，修改中台业务数据
                    String gmt_payment = new String(request.getParameter("gmt_payment").getBytes("ISO-8859-1"),"UTF-8");

                    if (null != inBills && inBills.getStatus() != 1){
                        inBills.setStatus(1);
                        inBills.setOrderId(trade_no);
                        inBills.setPayTime(DateUtils.convert(gmt_payment).getTime());
                        inBills.setMsg("支付宝h5回调成功");
                        boolean bool = inBillsService.updateById(inBills);
                        //如果更新成功则通知商户
                        if (bool){
                            //TODO 通知商户
                            NotifyRequest notifyRequest = new NotifyRequest();
                            notifyRequest.setMerchantBillNo(inBills.getMerchantBillNo());
                            notifyRequest.setBillNo(inBills.getBillNo());
                            notifyRequest.setStatus(inBills.getStatus());
                            notifyRequest.setMsg("支付回调");
                            notifyRequest.setType(1);
                            notifyRequest.setTransTime(inBills.getPayTime());//交易时间
                            if(StringUtils.isNotEmpty(inBills.getNotifyUrl())) {
                                notifyMerchantService.postMerchant(notifyRequest, inBills.getNotifyUrl(), inBills.getMerchantCode());//通知给商家
                            }
                        }
                        inNotifyLog.setStatus(1);
                        inNotifyLog.setBillNo(inBills.getBillNo());//支付中台生产的uuid，如需要 在inbill表查询

                    }else{
                        return;
                    }
                    inNotifyLogService.insert(inNotifyLog);
                }else {//退款
                    log.debug("支付宝退款回调开始-----" );
                    //TODO 记录主体回调数据
                    OutNotifyLog outNotifyLog = new OutNotifyLog();
                    outNotifyLog.setCallbackText(JSON.toJSONString(requestParams));
                    outNotifyLog.setMerchantBillNo(out_trade_no);
                    outNotifyLog.setStatus(0);
                    outNotifyLog.setTransNo(trade_no);
                    //TODO 接收回调，修改中台业务数据
                    if(refundBills != null && refundBills.getStatus() != 1){
                        refundBills.setStatus(1);
                        refundBills.setMsg("支付宝h5退款成功");
                        refundBills.setOutRequestNo(trade_no);
                        boolean bool = refundBillsService.updateById(refundBills);
                        //如果更新成功则通知商户
                        if (bool){
                            //TODO 通知商户
                            NotifyRequest notifyRequest = new NotifyRequest();
                            notifyRequest.setMerchantBillNo(refundBills.getMerchantBillNo());
                            notifyRequest.setMerchantRefundNo(refundBills.getMerchantRefundNo());
                            notifyRequest.setStatus(refundBills.getStatus());
                            notifyRequest.setMsg("退款回调");
                            notifyRequest.setType(1);
                            notifyRequest.setTransTime(refundBills.getRefundTime());//交易时间
                            if(StringUtils.isNotEmpty(refundBills.getNotifyUrl())) {
                                notifyMerchantService.postMerchant(notifyRequest, refundBills.getNotifyUrl(), refundBills.getMerchantCode());//通知给商家
                            }
                        }
                        outNotifyLog.setStatus(1);
                        outNotifyLog.setBillNo(refundBills.getRefundNo());//支付中台生产的uuid，如需要 在inbill表查询
                        outNotifyLogService.insert(outNotifyLog);
                    }
                }
            }else if("TRADE_CLOSED".equals(trade_status)){
                log.debug("支付宝退款回调开始-----" );
                //TODO 记录主体回调数据
                OutNotifyLog outNotifyLog = new OutNotifyLog();
                outNotifyLog.setCallbackText(JSON.toJSONString(requestParams));
                outNotifyLog.setMerchantBillNo(out_trade_no);
                outNotifyLog.setStatus(0);
                outNotifyLog.setTransNo(trade_no);
                //TODO 接收回调，修改中台业务数据
                if(refundBills != null && refundBills.getStatus() != 1){
                    refundBills.setStatus(1);
                    refundBills.setMsg("支付宝h5退款成功");
                    refundBills.setOutRequestNo(trade_no);
                    boolean bool = refundBillsService.updateById(refundBills);
                    //如果更新成功则通知商户
                    if (bool){
                        //TODO 通知商户
                        NotifyRequest notifyRequest = new NotifyRequest();
                        notifyRequest.setMerchantBillNo(refundBills.getMerchantBillNo());
                        notifyRequest.setMerchantRefundNo(refundBills.getMerchantRefundNo());
                        notifyRequest.setStatus(refundBills.getStatus());
                        notifyRequest.setMsg("退款回调");
                        notifyRequest.setType(1);
                        notifyRequest.setTransTime(refundBills.getRefundTime());//交易时间
                        if(StringUtils.isNotEmpty(refundBills.getNotifyUrl())) {
                            notifyMerchantService.postMerchant(notifyRequest, refundBills.getNotifyUrl(), refundBills.getMerchantCode());//通知给商家
                        }
                    }
                    outNotifyLog.setStatus(1);
                    outNotifyLog.setBillNo(refundBills.getRefundNo());//支付中台生产的uuid，如需要 在inbill表查询
                    outNotifyLogService.insert(outNotifyLog);
                }

            }
            log.info("支付成功...");
        }else {//验证失败
            log.info("支付, 验签失败...");
        }
    }
}
